﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using UnityScriptEngine;
namespace MBB_Payroll_Terminal
{
    public partial class frmExportImages : Form
    {
        string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MBB Terminal Data Sec\\";
        Threader t = new Threader();

        public frmExportImages()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            txtFrom.Value = DateTime.Now;
            txtTo.Value = txtFrom.Value.AddDays(1);

            DoEvents();
            DoAsyncEvents();
        }
        void DoAsyncEvents()
        {
            t.MethodCompleted += new EventHandler(delegate(object sender, EventArgs e)
            {
                t.SafeCall(this, delegate
                {
                    ControlState(true);
                });
            });
        }
        void DoEvents()
        {
            txtFrom.ValueChanged += new EventHandler(delegate
            {
                if (txtTo.Value < txtFrom.Value)
                {
                    MessageBox.Show("To Date must not be earlier than From date.");
                    txtTo.Value = txtFrom.Value.AddDays(1);
                    return;
                }
            });
            txtTo.ValueChanged += new EventHandler(delegate
            {
                if (txtTo.Value < txtFrom.Value)
                {
                    MessageBox.Show("To Date must not be earlier than From date.");
                    txtTo.Value = txtFrom.Value.AddDays(1);
                    return;
                }
            });
            btnSearch.Click += new EventHandler(delegate
            {
                GetFolders();
            });
            lstDate.DoubleClick += new EventHandler(delegate
            {
                GetImages();
            });
            lstImage.SelectedIndexChanged += new EventHandler(delegate
            {
                if (lstImage.SelectedIndex == -1) return;
                picCurrent.Image = new Bitmap(imgs[lstImage.SelectedIndex]);
            });
            btnExport.Click += new EventHandler(delegate
            {
                if (lstDate.Items.Count == 0)
                {
                    MessageBox.Show("Search result is empty.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                FolderBrowserDialog dlg = new FolderBrowserDialog();
                dlg.Description = "Export Path";
                dlg.RootFolder = Environment.SpecialFolder.MyComputer;
                dlg.ShowNewFolderButton = true;
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ControlState(false);
                    t.MethodCall(delegate{
                        ExportImages(dlg.SelectedPath + "\\");
                    });
                }
            });
            btnCancelExport.Click += new EventHandler(delegate
            {
                cancelExport = true;
            });
        }
        //Get folder list
        List<string> fldr = new List<string>();
        void GetFolders()
        {
            fldr = new List<string>();
            DateTime curDate = txtFrom.Value;
            while (curDate <= txtTo.Value)
            {
                if(Directory.Exists(path + curDate.ToString("yyyy-MM-dd"))) fldr.Add(curDate.ToString("yyyy-MM-dd"));
                curDate = curDate.AddDays(1);
            }

            lstDate.Items.Clear();
            lstDate.Items.AddRange(fldr.ToArray());
        }

        //Get Images
        string selDate = "";
        List<string> imgs = new List<string>();
        List<string> timgs = new List<string>();
        void GetImages()
        {
            if (lstDate.SelectedIndex == -1) return;
            selDate = lstDate.SelectedItem.ToString();
            imgs = new List<string>();
            imgs.AddRange(Directory.GetFiles(path + selDate));

            timgs = new List<string>();
            for (int i = 0; i < imgs.Count; i++)
            {
                string[] buf = imgs[i].Split('\\');
                timgs.Add(buf[buf.Length-1]);
            }
            lstImage.Items.Clear();
            lstImage.Items.AddRange(timgs.ToArray());
        }

        //Export images
        bool cancelExport = false;
        void ExportImages(string expPath)
        {
            List<string> dimgs = new List<string>();
            float expProg = 0f;
            cancelExport = false;
            for (int i = 0; i < fldr.Count; i++)
            {
                expProg = ((float)(i+1) / (float)fldr.Count) * 100f;
                //Check if directory is present.
                if (!Directory.Exists(expPath + fldr[i]))
                {
                    Directory.CreateDirectory(expPath + fldr[i]);
                }
                else
                {
                    //Check if directory is not empty
                    if (Directory.GetFiles(expPath + fldr[i]).Length > 0)
                    {
                        MessageBox.Show("The Current Directory is NOT empty", "Export Images", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                //Get the image list.
                dimgs = new List<string>();
                dimgs.AddRange(Directory.GetFiles(path + fldr[i]));
                for (int d = 0; d < dimgs.Count; d++)
                {
                    if (cancelExport) return;
                    try
                    {
                        string[] buf = dimgs[d].Split('\\');
                        UpdateProgress((int)expProg, buf[buf.Length - 1] + ".jpg");
                        File.Copy(dimgs[d], expPath + fldr[i] + "\\" + buf[buf.Length - 1] + ".jpg");
                        if (cancelExport) return;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                
            }
            UpdateProgress(100, "done.");
            System.Threading.Thread.Sleep(2000);
        }
        void UpdateProgress(int prg, string curFile)
        {
            t.SafeCall(this, delegate
            {
                prgWait.Value = prg;
                txtCurFile.Text = "Exporting " + curFile;
            });
        }
        //GUI
        void ControlState(bool enable)
        {
            txtFrom.Enabled = enable;
            txtTo.Enabled = enable;
            lstDate.Enabled = enable;
            lstImage.Enabled = enable;
            btnExport.Enabled = enable;
            btnSearch.Enabled = enable;
            btnClose.Enabled = enable;
            pnlMsg.Visible = !enable;
        }
    }
}
